package com.mbc.common;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

public class DataXML {
	public ArrayList<String[]> getDSNames(String filePath) throws Exception
	{
		try {
			String l_dataSourcesXml = filePath;
			SAXBuilder l_builder = new SAXBuilder();
			File l_dsXML = new File(l_dataSourcesXml);
			Document l_dsXMLDoc = (Document)l_builder.build(l_dsXML);
			Element l_RootElement = l_dsXMLDoc.getRootElement();
			List<Element> l_dsElements = l_RootElement.getChildren();
			ArrayList<String[]> l_dsNames = new ArrayList<String[]>();
			for (Element l_ele : l_dsElements) {
				l_dsNames.add(new String[]{l_ele.getAttributeValue("name"),l_ele.getAttributeValue("description")});
			}
			return l_dsNames;
		} catch (Exception e) {
			throw e;
		}
	}
	
	public String getDefaultDS(String filePath)throws Exception{
		try {
			String l_dataSourcesXml = filePath;
			SAXBuilder l_builder = new SAXBuilder();
			File l_dsXML = new File(l_dataSourcesXml);
			Document l_dsXMLDoc = (Document)l_builder.build(l_dsXML);
			Element l_RootElement = l_dsXMLDoc.getRootElement();
			List<Element> l_dsElements = l_RootElement.getChildren();
			String l_defaultDS = "";
			for (Element l_ele : l_dsElements) {
				if(Boolean.parseBoolean(l_ele.getAttributeValue("default"))){
					l_defaultDS = l_ele.getAttributeValue("name");
					break;
				}
			}
			return l_defaultDS;
		} catch (Exception e) {
			throw e;
		}
	}

	public Properties getDSProperties(String filePath)throws Exception
	{
		Properties l_properties = new Properties();
		
		try {
			String l_ds_file_path = filePath;
			SAXBuilder l_builder = new SAXBuilder();
			File l_file = new File(l_ds_file_path);
			Document l_xmlDoc = (Document)l_builder.build(l_file);
			Element l_rootElement = l_xmlDoc.getRootElement();
			List<Element> l_childList = l_rootElement.getChildren();
			for (Element l_child : l_childList) {
				l_properties.put(l_child.getAttributeValue("name"), l_child.getText());
			}
		} catch (Exception e) {
			throw e;
		}
		
		return l_properties;
	}
}
